package com.ipcamera.demo.h5.view;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.os.PersistableBundle;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.TextView;


import com.github.lzyzsd.jsbridge.BridgeWebView;
import com.ipcamer.demo.R;
import com.ipcamera.demo.h5.H5Info;
import com.ipcamera.demo.h5.contract.H5Contract;
import com.ipcamera.demo.h5.contract.JsPayParams;
import com.ipcamera.demo.h5.contract.PayParams;
import com.ipcamera.demo.h5.presenter.H5Presenter;

import org.json.JSONArray;
import org.json.JSONObject;

import java.util.HashMap;
import java.util.Locale;
import java.util.Map;


public class H5Activity extends MVPBaseActivity<H5Presenter> implements H5Contract.View {

    private final String oemid = "OEM";
    private static final int RESULT_CODE_QRCODE = 100;
    private static final int RESULT_CODE_PAY = 200;
    private static final int RESULT_CODE_SELECT_COUPON = 300;
    private static final int RESULT_CODE_PAY_SUCCESS = 400;
    private static final int PAYSUEECSS = 0x1234;

    BridgeWebView webView;
    H5Info mH5Info = new H5Info();//h5参数
    private String isShowOrder;
    private boolean isPay;
    private int pageCount;
    int count;
    Button orderbutton;

    public static final String URL_RENEW_4G_BASE = "https://payment-vstc-china.eye4.cn/";//"G4/v1?rgb='[254,02,77]'";//"+ "["+ 254+ "," + 2+ ","+ 77+"]"
    // public static final String URL_RENEW_4G2 = URL_RENEW_4G_BASE + "G4/?rgb="+"["+ 53+ "," + 132+ ","+ 219+"]";
    public static final String URL_RENEW_4G = URL_RENEW_4G_BASE + "G4";
    int FlowColor = Color.parseColor("#3584DB");
    int red = (FlowColor & 0xff0000) >> 16;
    int green = (FlowColor & 0x00ff00) >> 8;
    int blue = (FlowColor & 0x0000ff);
    String color = "[" + red + "," + green + "," + blue + "]";
    public String url = URL_RENEW_4G + "/?rgb=" + color + "&oemId=" + "OEM"+"&H5pay=1";

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState, @Nullable PersistableBundle persistentState) {
        super.onCreate(savedInstanceState, persistentState);

        mPresenter.initWeb(webView, mH5Info);
        Map<String, String> extraHeaders = new HashMap<String, String>();
        extraHeaders.put("oemid", oemid);
        Log.e("vst","mH5Info.url"+mH5Info.url);
        webView.loadUrl(mH5Info.url, extraHeaders);

    }

    @Override
    protected int getLayout() {
        return R.layout.activity_h5;
    }

    @Override
    protected void initBundleData(Intent i) {
        Log.e("vst","inutbundle");

    }

    @Override
    protected void initView() {
        webView = (BridgeWebView)findViewById(R.id.webView);
        orderbutton = (Button)findViewById(R.id.orderbutton);
    }

    @Override
    protected void initData() {
        Log.e("vst","init date");
        mH5Info.url = URL_RENEW_4G + "/?rgb=" + color + "&oemId=" + "OEM"+"&H5pay=1";
        mH5Info.uid = "10605921";
        mH5Info.ccid = "8986111925308095937";
        mH5Info.signa = "3";
        mH5Info.operator = "CTCC";
        webView = (BridgeWebView)findViewById(R.id.webView);
        mPresenter.initWeb(webView, mH5Info);
        Map<String, String> extraHeaders = new HashMap<String, String>();
        extraHeaders.put("oemid", oemid);
        Log.e("vst","mH5Info.url"+mH5Info.url);
        webView.loadUrl(mH5Info.url, extraHeaders);
        mPresenter.initWeb(webView, mH5Info);
        Log.e("vst","mH5Info.url"+mH5Info.url);

    }

    @Override
    protected void onClickEvent(View v) {
        switch (v.getId()) {

        }
    }

    @Override
    public void setTitle(String title) {

    }

    @Override
    public void configNavigationBarColor(String hexColor) {
        //默认颜色

    }

    @Override
    public void configNavigationBarOrder(String isShow) {

    }

    @Override
    public void configNavigationBarOrderCno(String cNo) {

    }

    @Override
    public void configNavigationBarRightButtoninfo(String info) {
        isShowOrder = "1";
        try {
            JSONArray jsonArray = new JSONArray(info);
            for (int i = 0; i < jsonArray.length(); i++) {
                try {
                    JSONObject obj = jsonArray.getJSONObject(i);
                    mH5Info.orderUrl = obj.optString("url");
                } catch (Exception e) {
                }
            }
        } catch (Exception e) {
        }

        orderbutton.setVisibility(View.VISIBLE);
        orderbutton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                isShowOrder = "0";
                orderbutton.setVisibility(View.GONE);
                Map<String, String> extraHeaders = new HashMap<String, String>();
                extraHeaders.put("oemid", oemid);
                extraHeaders.put("userid", mH5Info.uid);
                extraHeaders.put("language", Locale.getDefault().getLanguage());
                extraHeaders.put("cNo", mH5Info.ccid);
                webView.loadUrl(mH5Info.orderUrl, extraHeaders);
                Log.e("vst", "orderUrl" + mH5Info.orderUrl);
            }
        });
    }

    @Override
    public void configNavigationBarHidden(boolean isHidden) {

    }

    @Override
    public void configStatusBarHidden(boolean isHidden) {

    }

    @Override
    public void configStatusBarStyle(boolean isBlack) {

    }

    @Override
    public void scanPage() {

    }

    @Override
    public void displayDiscountCoupon(String productId) {

    }

    @Override
    public void newPage(String url) {
        //加载新页面
        Log.e("veepai","newPage url"+url);
        isShowOrder = "0";
        if (!TextUtils.isEmpty(url)) {
            count += 1;
            orderbutton.setVisibility(View.GONE);
            Log.e("veepai","newPage url"+url);
            webView.loadUrl(url);
            showOrHideEmptyTitleBar(true);
        }
    }

    private PayParams mPayParams;

    @Override
    public void payPage(PayParams params) {
    }

    @Override
    public void paySuccessPage(String title, String money, String orderId, String type) {
        openPaySuccessActivity(TextUtils.equals("orderSettlement", type), title, money, orderId);
    }

    @Override
    public void showMessage(String str) {

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        //激活绑定优惠券
        if (requestCode == RESULT_CODE_QRCODE && resultCode == RESULT_OK && data != null) {
            //{"ACT":"addTicket","id":"1800","code":"59SD9mVzRKlZmVOo"}
            String result = data.getStringExtra("scanResult");
            //回调扫码结果
            mPresenter.scanCouponResult(result);
        }
        //选择优惠券
        if (requestCode == RESULT_CODE_SELECT_COUPON && resultCode == RESULT_OK && data != null) {

        }

        //支付成功
        if (requestCode == RESULT_CODE_PAY) {
            if (resultCode == PAYSUEECSS) {
//                //从缓存支付参数中获取
//                String productName = mPayParams == null ? null : mPayParams.getTitle();
//                String paymentAmount = mPayParams == null ? null : mPayParams.getMoney();
//                String orderNo = mPayParams == null ? null : mPayParams.getOrderId();
//                //跳转到充值成功页面
//                openPaySuccessActivity(false, productName, paymentAmount, orderNo);

                //从缓存支付参数中获取
                String productName = mPayParams == null ? null : mPayParams.getTitle();
                String paymentAmount = mPayParams == null ? null : mPayParams.getMoney();
                String orderNo = mPayParams == null ? null : mPayParams.getOrderId();
                //跳转到充值成功页面
                Log.e("vst", "suc2");
                if (mH5Info.ccid != null && !mH5Info.ccid.equals("")) {
                    // TODO: 2020-01-14 HJH支付成功跳转
                    String paystatus = data.getStringExtra("paystatus");
                    Log.e("vst", "paystatus" + paystatus);
                    if (paystatus.equals("0")) {
                        finish();
                    } else if (paystatus.equals("1")) {
                        Map<String, String> extraHeaders = new HashMap<String, String>();
                        extraHeaders.put("oemid", oemid);
                        extraHeaders.put("userid", "1233");
                        extraHeaders.put("cNo", mH5Info.ccid);
                        extraHeaders.put("language", Locale.getDefault().getLanguage());
                        webView.loadUrl(mH5Info.orderUrl, extraHeaders);
                    } else {
                        finish();
                    }
                } else {
                    openPaySuccessActivity(false, productName, paymentAmount, orderNo);
                }
            } else {
                //失败 重新加载页面
                webView.reload();
            }
        }

        //支付/充值成功页面返回
        if (requestCode == RESULT_CODE_PAY_SUCCESS && resultCode == RESULT_OK) {
            if (isPay) {
                //如果是支付成功，回到首页
                pageCount = 0;
                showOrHideEmptyTitleBar(false);
                mPresenter.setClearHistory();
                webView.loadUrl(mH5Info.url);
            } else {
                // 充值成功 返回上一H5页面（支付是在余额页面调起支付，返回上一页即订单页面）
                onBackPressed();
            }
        }
    }

    private void showOrHideEmptyTitleBar(boolean isOpenNewPage) {
        //showDialog(getString(R.string.in_the_load));
       // LogUtils.i("----------------------" + "载入中");
    }

    @Override
    public void onBackPressed() {
        Log.e("veepai","count"+count);

        Log.e("veepai","isShowOrder"+isShowOrder);
        if (mH5Info.ccid != null && !mH5Info.ccid.equals("") && isShowOrder != null && isShowOrder.equals("0")) {
            webView.goBack();
            showOrHideEmptyTitleBar(false);
            return;
        }
        super.onBackPressed();
    }

    private void openPaySuccessActivity(boolean isPay, String productName, String paymentAmount, String orderNo) {
        this.isPay = isPay;
       // H5PaySuccessActivity.openForResult(this, RESULT_CODE_PAY_SUCCESS, isPay, productName, paymentAmount, orderNo);
    }

    @Override
    public void closeDialog() {

    }

    @Override
    public void googleBuyAction(JsPayParams jsPayParams) {

    }

    @Override
    protected H5Presenter getPresenter() {
        return new H5Presenter(this);
    }
}
